package com.tjvib.presenter;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.common.Callback;
import com.tjvib.sensor.LocalSensorData;
import com.tjvib.service.LocalSensorService;
import com.tjvib.util.ToastUtil;
import com.tjvib.view.activity.LocalSensorActivity;

import java.util.TimerTask;

public class LocalSensorPresenter extends SensorPresenter<LocalSensorService, LocalSensorActivity> {

    private static final String TAG = "LocalSensorPresenter";

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocalSensorService.LocalBinder binder = (LocalSensorService.LocalBinder) service;
            mService = (LocalSensorService) binder.getService();
            bound = true;
            mService.connectSensor();
            startReadingData();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            stopReadingData();
            bound = false;
        }
    };

    private TimerTask readDataTask = new TimerTask() {
        @Override
        public void run() {
            if (bound) {
                LocalSensorData data = mService.getData();
                if (data == null)
                    return;
                view.setData(data);
            }
        }
    };

    public LocalSensorPresenter(LocalSensorActivity view) {
        super(view);
    }

    @Override
    public ServiceConnection getServiceConnection() {
        return mConnection;
    }

    @Override
    public Class<?> getServiceClass() {
        return LocalSensorService.class;
    }

    @Override
    public TimerTask getReadDataTask() {
        return readDataTask;
    }

    /*@Override
    public Runnable getReadDataRunnable() {
        return updateUI;
    }*/

    @Override
    public void setStreamFreq(int freq) {
        if (mService != null)
            mService.setStreamFrequency(freq);
        else
            ToastUtil.show("服务未启动");
    }

    @Override
    public int getStreamFreq() {
        return mService.getStreamFrequency();
    }

    @Override
    public void discardData() {
        if (mService != null)
            mService.discardData();
        else
            ToastUtil.show("服务未启动");
    }

    @Override
    public void storeData(String dataName, Callback callback) {
        if (mService != null)
            mService.storeData(dataName, callback);
        else
            ToastUtil.show("服务未启动");
    }

    @Override
    public void resetTimestamp() {
        if (mService != null)
            mService.resetTimestamp();
        else
            ToastUtil.show("服务未启动");
    }

    @Override
    public String getDataSetType() {
        return "local";
    }

    @Override
    String getTag() {
        return TAG;
    }
}
